package basicobject

import (
	"strconv"
	"yizhuoyan/go-study/pdfgo/handyio"
)

type Integer struct {
	value int
}

func NewInteger(v int) *Integer {
	return &Integer{value: v}
}
func (this *Integer) ValueInt64() int64 {
	return int64(this.value)
}
func (this *Integer) ValueInt() int {
	return this.value
}

func (this *Integer) Serialize(w handyio.PdfRawWriter) error {
	w.WriteBytes([]byte(strconv.FormatInt(int64(this.value), 10)))
	return nil
}
func (this *Integer) UnSerialize(r handyio.PdfRawReader) error {
	startAt := r.IndexCurrent()
	if r.NextByteEquals('+') {
		rst, err := UnSerializeNoSignInt64(r)
		if err != nil {
			_ = r.IndexMoveTo(startAt)
			return err
		}
		this.value = rst
		return nil
	}
	if r.NextByteEquals('-') {
		rst, err := UnSerializeNoSignInt64(r)
		if err != nil {
			_ = r.IndexMoveTo(startAt)
			return err
		}
		this.value = -rst
		return nil
	}
	rst, err := UnSerializeNoSignInt64(r)
	if err != nil {
		_ = r.IndexMoveTo(startAt)
		return err
	}
	this.value = rst

	return nil
}

func UnSerializeNoSignInt64(r handyio.PdfRawReader) (int, error) {
	rst := r.NextBytes(func(b byte) int {
		switch b {
		case '0', '1', '2', '3', '4', '5', '6', '7', '8', '9':
			return handyio.ReadNext
		}
		return handyio.ReadStop
	})
	if len(rst) == 0 {
		return 0, r.NotSupport("无数字")
	}
	//有点
	if r.NextByteEquals('.') {
		return 0, r.NotSupport("非整数")
	}
	v, err := strconv.ParseInt(string(rst), 10, 32)
	if err != nil {
		//超出int范围？？
		return 0, err
	}
	return int(v), nil
}
